import {
  ArrowDownIcon,
  ArrowUpIcon,
  CheckIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  CopyIcon,
  PencilIcon,
  RefreshCwIcon,
  Square,
  ThumbsUp,
  ThumbsDown,
  MoreHorizontal,
  Trash2,
} from "lucide-react";

import {
  ActionBarPrimitive,
  BranchPickerPrimitive,
  ComposerPrimitive,
  ErrorPrimitive,
  MessagePrimitive,
  ThreadPrimitive,
  useMessage,
} from "@assistant-ui/react";

import type { FC } from "react";
import * as React from "react";
import { LazyMotion, MotionConfig, domAnimation } from "motion/react";
import * as m from "motion/react-m";

import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { MarkdownText } from "@/components/assistant-ui/markdown-text";
import { ToolFallback } from "@/components/assistant-ui/tool-fallback";
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
import { ComposerToolbar } from "@/components/composer/ComposerToolbar";
import { ImageUpload, type ImageFile } from "@/components/vision/ImageUpload";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { ErrorMessage } from "@/components/ui/error-message";
import { useAssistantStore } from "@/store/assistant";
import { useSubAgentContext } from "@/lib/sidecar-runtime";
import { AgentThinkingProcess } from "@/components/agent/AgentThinkingProcess";
import { ToolCallVisualization } from "@/components/tools/ToolCallVisualization";
import { WelcomeScreen } from "@/components/welcome/WelcomeScreen";
import { ThinkingChainViewer } from "@/components/thinking/ThinkingChainViewer";
import { parseThinkingChain } from "@/lib/thinking-parser";

import { cn } from "@/lib/utils";

export const Thread: FC = () => {
  // 动态计算最优宽度
  const [maxWidth, setMaxWidth] = React.useState("44rem");
  
  React.useEffect(() => {
    const updateWidth = () => {
      const screenWidth = window.innerWidth;
      
      // 根据屏幕宽度动态计算内容区域宽度
      // 考虑侧边栏宽度（约 300-400px）
      if (screenWidth >= 1920) {
        setMaxWidth("min(1400px, calc(100vw - 500px))");
      } else if (screenWidth >= 1440) {
        setMaxWidth("min(1100px, calc(100vw - 400px))");
      } else if (screenWidth >= 1024) {
        setMaxWidth("min(900px, calc(100vw - 350px))");
      } else {
        setMaxWidth("calc(100vw - 2rem)"); // 移动端
      }
    };
    
    updateWidth();
    window.addEventListener('resize', updateWidth);
    return () => window.removeEventListener('resize', updateWidth);
  }, []);
  
  return (
    <LazyMotion features={domAnimation}>
      <MotionConfig reducedMotion="user">
        <ThreadPrimitive.Root
          className="aui-root aui-thread-root"
          style={{
            ["--thread-max-width" as string]: maxWidth,
          }}
        >
          <ThreadPrimitive.Viewport className="aui-thread-viewport">
            <ThreadPrimitive.If empty>
              <ThreadWelcome />
            </ThreadPrimitive.If>

            <ThreadPrimitive.Messages
              components={{
                UserMessage,
                EditComposer,
                AssistantMessage,
              }}
            />

            <ThreadPrimitive.If empty={false}>
              <div className="aui-thread-viewport-spacer" />
            </ThreadPrimitive.If>

            <Composer />
          </ThreadPrimitive.Viewport>
        </ThreadPrimitive.Root>
      </MotionConfig>
    </LazyMotion>
  );
};

const ThreadScrollToBottom: FC = () => {
  return (
    <ThreadPrimitive.ScrollToBottom asChild>
      <TooltipIconButton
        tooltip="Scroll to bottom"
        variant="outline"
        className="aui-thread-scroll-to-bottom"
      >
        <ArrowDownIcon />
      </TooltipIconButton>
    </ThreadPrimitive.ScrollToBottom>
  );
};

const ThreadWelcome: FC = () => {
  return (
    <div className="aui-thread-welcome-root welcome-screen">
      <WelcomeScreen />
    </div>
  );
};

const ThreadSuggestions: FC = () => {
  // This component is now handled within WelcomeScreen
  return null;
};

const Composer: FC = () => {
  const [placeholderIndex, setPlaceholderIndex] = React.useState(0);
  const [textLength, setTextLength] = React.useState(0);
  const [uploadedImages, setUploadedImages] = React.useState<ImageFile[]>([]);
  const [showImageUpload, setShowImageUpload] = React.useState(false);
  
  const placeholders = [
    "有什么可以帮你的？",
    "试试上传图片问我...",
    "按 / 查看快捷命令",
    "Shift + Enter 换行",
  ];
  
  // Rotate placeholder every 5 seconds
  React.useEffect(() => {
    const interval = setInterval(() => {
      setPlaceholderIndex((prev) => (prev + 1) % placeholders.length);
    }, 5000);
    return () => clearInterval(interval);
  }, []);
  
  // Handle image uploads
  const handleImagesChange = React.useCallback((images: ImageFile[]) => {
    setUploadedImages(images);
  }, []);
  
  const handleFileSelect = (files: File[]) => {
    // Toggle image upload panel
    setShowImageUpload(true);
  };

  const handleEmojiSelect = (emoji: string) => {
    // 插入表情到输入框
    const input = document.querySelector('.aui-composer-input') as HTMLTextAreaElement;
    if (input) {
      const start = input.selectionStart || 0;
      const end = input.selectionEnd || 0;
      const text = input.value;
      const newText = text.slice(0, start) + emoji + text.slice(end);
      
      // 触发 input 事件以更新 assistant-ui 的状态
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
        window.HTMLTextAreaElement.prototype,
        'value'
      )?.set;
      nativeInputValueSetter?.call(input, newText);
      
      const event = new Event('input', { bubbles: true });
      input.dispatchEvent(event);
      
      // 恢复光标位置
      setTimeout(() => {
        input.selectionStart = input.selectionEnd = start + emoji.length;
        input.focus();
      }, 0);
    }
  };

  const handleCodeInsert = (code: string, language?: string) => {
    // 插入代码块到输入框
    const input = document.querySelector('.aui-composer-input') as HTMLTextAreaElement;
    if (input) {
      const codeBlock = `\`\`\`${language || ''}\n${code}\n\`\`\``;
      const start = input.selectionStart || 0;
      const text = input.value;
      const newText = text.slice(0, start) + codeBlock + text.slice(start);
      
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
        window.HTMLTextAreaElement.prototype,
        'value'
      )?.set;
      nativeInputValueSetter?.call(input, newText);
      
      const event = new Event('input', { bubbles: true });
      input.dispatchEvent(event);
      
      setTimeout(() => {
        input.selectionStart = input.selectionEnd = start + codeBlock.length;
        input.focus();
      }, 0);
    }
  };

  const handleLinkInsert = (url: string, text?: string) => {
    // 插入链接到输入框
    const input = document.querySelector('.aui-composer-input') as HTMLTextAreaElement;
    if (input) {
      const link = text ? `[${text}](${url})` : url;
      const start = input.selectionStart || 0;
      const currentText = input.value;
      const newText = currentText.slice(0, start) + link + currentText.slice(start);
      
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
        window.HTMLTextAreaElement.prototype,
        'value'
      )?.set;
      nativeInputValueSetter?.call(input, newText);
      
      const event = new Event('input', { bubbles: true });
      input.dispatchEvent(event);
      
      setTimeout(() => {
        input.selectionStart = input.selectionEnd = start + link.length;
        input.focus();
      }, 0);
    }
  };

  const handlePromptTemplateSelect = (prompt: string) => {
    // 插入提示词模板到输入框
    const input = document.querySelector('.aui-composer-input') as HTMLTextAreaElement;
    if (input) {
      // 如果输入框为空，直接替换；否则在当前位置插入
      const start = input.selectionStart || 0;
      const currentText = input.value;
      const newText = currentText ? currentText.slice(0, start) + '\n' + prompt + currentText.slice(start) : prompt;
      
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
        window.HTMLTextAreaElement.prototype,
        'value'
      )?.set;
      nativeInputValueSetter?.call(input, newText);
      
      const event = new Event('input', { bubbles: true });
      input.dispatchEvent(event);
      
      setTimeout(() => {
        input.selectionStart = input.selectionEnd = newText.length;
        input.focus();
      }, 0);
    }
  };

  return (
    <div className="aui-composer-wrapper">
      <ThreadScrollToBottom />
      <ComposerPrimitive.Root className="aui-composer-root">
        {/* Enhanced Toolbar */}
        <div className="border-t border-border px-4 pt-3 pb-2">
          <ComposerToolbar
            onFileSelect={handleFileSelect}
            onEmojiSelect={handleEmojiSelect}
            onCodeInsert={handleCodeInsert}
            onLinkInsert={handleLinkInsert}
            onPromptTemplateSelect={handlePromptTemplateSelect}
          />
        </div>
        
        {/* Image Upload Panel */}
        {showImageUpload && (
          <div className="px-4 pb-2">
            <div className="mb-2 flex items-center justify-between">
              <span className="text-sm font-medium">上传图片</span>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setShowImageUpload(false)}
                className="h-6 px-2"
              >
                收起
              </Button>
            </div>
            <ImageUpload
              maxImages={5}
              onImagesChange={handleImagesChange}
              className="max-w-full"
            />
          </div>
        )}
        
        {/* Enhanced Input with dynamic placeholder */}
        <div className="relative">
          <ComposerPrimitive.Input
            placeholder={placeholders[placeholderIndex]}
            className="aui-composer-input transition-all"
            rows={1}
            autoFocus
            aria-label="Message input"
            onChange={(e) => setTextLength(e.target.value.length)}
          />
          
          {/* Character count */}
          {textLength > 0 && (
            <div className="absolute right-4 bottom-2 text-xs text-muted-foreground/60 pointer-events-none">
              {textLength} / 4000
            </div>
          )}
        </div>
        
        <ComposerAction />
      </ComposerPrimitive.Root>
    </div>
  );
};

const ComposerAction: FC = () => {
  const [canSend, setCanSend] = React.useState(false);
  
  return (
    <div className="aui-composer-action-wrapper">
      <ThreadPrimitive.If running={false}>
        <ComposerPrimitive.Send asChild>
          <TooltipIconButton
            tooltip="Send message (Enter)"
            side="bottom"
            type="submit"
            variant="default"
            size="icon"
            className={cn(
              "aui-composer-send transition-all duration-200",
              canSend && "scale-110 shadow-md hover:scale-115"
            )}
            aria-label="Send message"
            onMouseEnter={() => setCanSend(true)}
            onMouseLeave={() => setCanSend(false)}
          >
            <ArrowUpIcon className="aui-composer-send-icon" />
          </TooltipIconButton>
        </ComposerPrimitive.Send>
      </ThreadPrimitive.If>

      <ThreadPrimitive.If running>
        <ComposerPrimitive.Cancel asChild>
          <Button
            type="button"
            variant="default"
            size="icon"
            className="aui-composer-cancel animate-pulse"
            aria-label="Stop generating"
          >
            <Square className="aui-composer-cancel-icon" />
          </Button>
        </ComposerPrimitive.Cancel>
      </ThreadPrimitive.If>
    </div>
  );
};

const MessageError: FC = () => {
  return (
    <MessagePrimitive.Error>
      <ErrorPrimitive.Root className="aui-message-error-root">
        <div className="flex items-start gap-3 p-4 rounded-lg bg-destructive/10 border border-destructive/30">
          <div className="p-2 rounded-lg bg-destructive/20 shrink-0">
            <Trash2 className="w-5 h-5 text-destructive" />
          </div>
          
          <div className="flex-1 min-w-0">
            <h4 className="font-semibold text-destructive mb-1">
              发生错误
            </h4>
            <p className="text-sm text-destructive/80 leading-relaxed">
              <ErrorPrimitive.Message />
            </p>
          </div>
          
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              // TODO: Implement retry logic
              console.log('Retry message');
            }}
            className="shrink-0 border-destructive/30 hover:bg-destructive/20 hover:border-destructive/50"
          >
            <RefreshCwIcon className="w-4 h-4 mr-2" />
            重试
          </Button>
        </div>
      </ErrorPrimitive.Root>
    </MessagePrimitive.Error>
  );
};

const MessageTimestamp: FC = () => {
  const message = useMessage();
  const createdAt = message.createdAt;
  
  if (!createdAt) return null;

  const formatTime = (date: Date) => {
          const now = new Date();
          const diff = now.getTime() - date.getTime();
          
          // 小于 1 分钟
          if (diff < 60000) {
            return '刚刚';
          }
          
          // 小于 1 小时
          if (diff < 3600000) {
            const minutes = Math.floor(diff / 60000);
            return `${minutes} 分钟前`;
          }
          
          // 小于 24 小时
          if (diff < 86400000) {
            const hours = Math.floor(diff / 3600000);
            return `${hours} 小时前`;
          }
          
          // 今年
          if (now.getFullYear() === date.getFullYear()) {
            return date.toLocaleString('zh-CN', {
              month: 'numeric',
              day: 'numeric',
              hour: '2-digit',
              minute: '2-digit',
            });
          }
          
          // 其他
          return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: 'numeric',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
          });
        };
  
  return <>{formatTime(createdAt)}</>;
};

const AssistantMessage: FC = () => {
  const selectedAssistant = useAssistantStore((state) => state.selectedAssistant);
  const { activeExecutions, toolCalls } = useSubAgentContext();
  const message = useMessage();
  
  // Parse thinking chain from message content
  const thinkingChain = React.useMemo(() => {
    if (!message.content || message.content.length === 0) return null;
    
    // Get text content from message
    const textContent = message.content
      .filter((part: any) => part.type === 'text')
      .map((part: any) => part.text)
      .join('\n');
    
    if (!textContent) return null;
    
    // Parse thinking chain
    return parseThinkingChain(message.id, textContent);
  }, [message.id, message.content]);
  
  return (
    <MessagePrimitive.Root asChild>
      <div
        className="aui-assistant-message-root"
        data-role="assistant"
      >
        {/* Enhanced Avatar with gradient */}
        <Avatar className="h-9 w-9 shrink-0 mt-1 shadow-md">
          <AvatarFallback className="bg-gradient-to-br from-blue-500 to-purple-600 text-white text-sm font-semibold">
            {selectedAssistant?.name?.[0] || '🤖'}
          </AvatarFallback>
        </Avatar>

        <div className="flex-1 space-y-2">
          {/* Enhanced header with better typography */}
          <div className="flex items-center gap-2">
            <span className="text-sm font-semibold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
              {selectedAssistant?.name || 'CAgent'}
            </span>
            <span className="text-xs text-muted-foreground/70">
              <MessageTimestamp />
            </span>
          </div>

          {/* Show loading indicator when message is being generated */}
          <ThreadPrimitive.If running>
            <div className="flex items-center gap-2 text-muted-foreground text-sm mb-2">
              <LoadingSpinner size="sm" variant="minimal" />
              <span className="loading-dots">
                <span></span>
                <span></span>
                <span></span>
              </span>
              <span>正在思考</span>
            </div>
          </ThreadPrimitive.If>

          {/* Show thinking process for active executions */}
          {activeExecutions.length > 0 && (
            <div className="mb-3">
              <AgentThinkingProcess
                executions={activeExecutions}
                showOnlyActive={true}
              />
            </div>
          )}

          {/* Show tool calls */}
          {toolCalls.length > 0 && (
            <div className="mb-3">
              <ToolCallVisualization toolCalls={toolCalls} />
            </div>
          )}

          {/* Show thinking chain if available */}
          {thinkingChain && (
            <div className="mb-3">
              <ThinkingChainViewer 
                chain={thinkingChain}
                defaultExpanded={false}
              />
            </div>
          )}

          <div className="aui-assistant-message-content">
            <MessagePrimitive.Parts
              components={{
                Text: MarkdownText,
                tools: { Fallback: ToolFallback },
              }}
            />
            <MessageError />
          </div>

          <div className="aui-assistant-message-footer">
            <BranchPicker />
            <AssistantActionBar />
          </div>
        </div>
      </div>
    </MessagePrimitive.Root>
  );
};

const AssistantActionBar: FC = () => {
  const message = useMessage();
  const [feedback, setFeedback] = React.useState<'like' | 'dislike' | null>(null);

  const handleFeedback = (type: 'like' | 'dislike') => {
    if (feedback === type) {
      setFeedback(null); // 取消反馈
    } else {
      setFeedback(type);
      // TODO: 保存反馈到数据库
      console.log(`Message ${message.id} feedback: ${type}`);
    }
  };

  return (
    <ActionBarPrimitive.Root
      hideWhenRunning
      autohide="not-last"
      autohideFloat="single-branch"
      className="aui-assistant-action-bar-root"
    >
      {/* Copy Button */}
      <ActionBarPrimitive.Copy asChild>
        <TooltipIconButton tooltip="复制">
          <MessagePrimitive.If copied>
            <CheckIcon />
          </MessagePrimitive.If>
          <MessagePrimitive.If copied={false}>
            <CopyIcon />
          </MessagePrimitive.If>
        </TooltipIconButton>
      </ActionBarPrimitive.Copy>

      {/* Reload Button */}
      <ActionBarPrimitive.Reload asChild>
        <TooltipIconButton tooltip="重新生成">
          <RefreshCwIcon />
        </TooltipIconButton>
      </ActionBarPrimitive.Reload>

      {/* Like Button */}
      <TooltipIconButton
        tooltip="有帮助"
        onClick={() => handleFeedback('like')}
        className={cn(
          "transition-colors",
          feedback === 'like' && "text-green-500 bg-green-500/10"
        )}
      >
        <ThumbsUp className={cn(
          "h-4 w-4",
          feedback === 'like' && "fill-current"
        )} />
      </TooltipIconButton>

      {/* Dislike Button */}
      <TooltipIconButton
        tooltip="没有帮助"
        onClick={() => handleFeedback('dislike')}
        className={cn(
          "transition-colors",
          feedback === 'dislike' && "text-red-500 bg-red-500/10"
        )}
      >
        <ThumbsDown className={cn(
          "h-4 w-4",
          feedback === 'dislike' && "fill-current"
        )} />
      </TooltipIconButton>
    </ActionBarPrimitive.Root>
  );
};

const UserMessage: FC = () => {
  return (
    <MessagePrimitive.Root asChild>
      <div
        className="aui-user-message-root"
        data-role="user"
      >
        <div className="flex-1 space-y-2">
          {/* Enhanced header with better typography */}
          <div className="flex items-center gap-2 justify-end">
            <span className="text-xs text-muted-foreground/70">
              <MessageTimestamp />
            </span>
            <span className="text-sm font-semibold text-primary">你</span>
          </div>

          <div className="aui-user-message-content-wrapper">
            <div className="aui-user-message-content">
              <MessagePrimitive.Parts />
            </div>
            <div className="aui-user-action-bar-wrapper">
              <UserActionBar />
            </div>
          </div>

          <BranchPicker className="aui-user-branch-picker" />
        </div>

        {/* Enhanced user avatar */}
        <Avatar className="h-9 w-9 shrink-0 mt-1 shadow-md">
          <AvatarFallback className="bg-gradient-to-br from-green-500 to-teal-600 text-white text-sm font-semibold">
            你
          </AvatarFallback>
        </Avatar>
      </div>
    </MessagePrimitive.Root>
  );
};

const UserActionBar: FC = () => {
  const message = useMessage();
  const [showDeleteConfirm, setShowDeleteConfirm] = React.useState(false);

  const handleDelete = () => {
    // TODO: 实现删除功能
    console.log(`Delete message: ${message.id}`);
    setShowDeleteConfirm(false);
  };

  return (
    <ActionBarPrimitive.Root
      hideWhenRunning
      autohide="not-last"
      className="aui-user-action-bar-root"
    >
      {/* Copy Button */}
      <ActionBarPrimitive.Copy asChild>
        <TooltipIconButton tooltip="复制">
          <MessagePrimitive.If copied>
            <CheckIcon />
          </MessagePrimitive.If>
          <MessagePrimitive.If copied={false}>
            <CopyIcon />
          </MessagePrimitive.If>
        </TooltipIconButton>
      </ActionBarPrimitive.Copy>

      {/* Edit Button */}
      <ActionBarPrimitive.Edit asChild>
        <TooltipIconButton tooltip="编辑" className="aui-user-action-edit">
          <PencilIcon />
        </TooltipIconButton>
      </ActionBarPrimitive.Edit>

      {/* Delete Button */}
      {!showDeleteConfirm ? (
        <TooltipIconButton
          tooltip="删除"
          onClick={() => setShowDeleteConfirm(true)}
          className="hover:text-destructive"
        >
          <Trash2 className="h-4 w-4" />
        </TooltipIconButton>
      ) : (
        <div className="flex items-center gap-1 px-2 py-1 rounded bg-destructive/10">
          <span className="text-xs text-destructive">确认删除？</span>
          <Button
            size="sm"
            variant="ghost"
            className="h-6 px-2 text-xs hover:bg-destructive hover:text-destructive-foreground"
            onClick={handleDelete}
          >
            删除
          </Button>
          <Button
            size="sm"
            variant="ghost"
            className="h-6 px-2 text-xs"
            onClick={() => setShowDeleteConfirm(false)}
          >
            取消
          </Button>
        </div>
      )}
    </ActionBarPrimitive.Root>
  );
};

const EditComposer: FC = () => {
  return (
    <div className="aui-edit-composer-wrapper">
      <ComposerPrimitive.Root className="aui-edit-composer-root">
        <ComposerPrimitive.Input
          className="aui-edit-composer-input"
          autoFocus
        />

        <div className="aui-edit-composer-footer">
          <ComposerPrimitive.Cancel asChild>
            <Button variant="ghost" size="sm" aria-label="Cancel edit">
              Cancel
            </Button>
          </ComposerPrimitive.Cancel>
          <ComposerPrimitive.Send asChild>
            <Button size="sm" aria-label="Update message">
              Update
            </Button>
          </ComposerPrimitive.Send>
        </div>
      </ComposerPrimitive.Root>
    </div>
  );
};

const BranchPicker: FC<BranchPickerPrimitive.Root.Props> = ({
  className,
  ...rest
}) => {
  return (
    <BranchPickerPrimitive.Root
      hideWhenSingleBranch
      className={cn("aui-branch-picker-root", className)}
      {...rest}
    >
      <BranchPickerPrimitive.Previous asChild>
        <TooltipIconButton tooltip="Previous">
          <ChevronLeftIcon />
        </TooltipIconButton>
      </BranchPickerPrimitive.Previous>
      <span className="aui-branch-picker-state">
        <BranchPickerPrimitive.Number /> / <BranchPickerPrimitive.Count />
      </span>
      <BranchPickerPrimitive.Next asChild>
        <TooltipIconButton tooltip="Next">
          <ChevronRightIcon />
        </TooltipIconButton>
      </BranchPickerPrimitive.Next>
    </BranchPickerPrimitive.Root>
  );
};

